<?php
class EmailsController extends Controller {
	public function index() {
		$this->getSmarty ();
		$this->smarty->display ( "admin/emails.tpl" );
	}
	
	public function getpage(){
		$this->getSmarty ();
		require_once SERVICE . DS . 'EmailsService.class.php';
		// START 数据库查询及分页数据
		$emailsService = new EmailsService ( $this->getDB () );
		
		$page = isset ( $_POST ['page'] ) ? intval ( $_POST ['page'] ) : 1;
		$rows = isset ( $_POST ['rows'] ) ? intval ( $_POST ['rows'] ) : 10;
		$offset = ($page - 1) * $rows;
		$result = array ();
		$row_count = $emailsService->countNum ();
		$email_infos = $emailsService->emailsPage ( $offset, $rows );
		
		$result ["total"] = $row_count;
		$result ["rows"] = $email_infos;
		echo json_encode ( $result );
	}
	
	public function delete() {
		require_once SERVICE . DS . 'EmailsService.class.php';
		$emailsService = new EmailsService ( $this->getDB () );
		$id = $_POST ['id'];
		$emailsService->deleteEmail ( $id );
		echo 1;
	}
	
	public function save() {
		require_once SERVICE . DS . 'EmailsService.class.php';
		
		$emailsService = new EmailsService ( $this->getDB () );
		
		$id = $_POST ["id"];
		if (empty ( $id )) {
			$input_data = array (
					'email' => $_POST ["email"],
					'email_origin' => $_POST ["email_origin"] ,
					'user_name' => $_POST ["user_name"],
					'create_date' => array( date("Y-m-d G:i:s"),'%Y-%m-%d %H:%i:%s'),
					'post_code' => $_POST ["post_code"],
					'country' => $_POST ["country"]
			);
			$format = array(
				"%s","%s","%s","%date","%s","%s"
			);
			$emailsService->addEmails( $input_data , $format);
		} else {
			$input_data = array (
					'email' => $_POST ["email"],
					'email_origin' => $_POST ["email_origin"],
					'user_name' => $_POST ["user_name"],
					'create_date' => array( date("Y-m-d G:i:s"),'%Y-%m-%d %H:%i:%s'),
					'post_code' => $_POST ["post_code"],
					'country' => $_POST ["country"]
			);
			
			$input_condition = array (
				'id' => $_POST ["id"] 
			);
			$format = array(
				"%s","%s","%s","%date","%s","%s"
			);
			$id = $emailsService->edit ( $input_data, $input_condition ,$format);
		}
		echo "1";
	}
}